/**
 * tarside-ftp -- A simple FTP client, using the ANSI C and GTK+.
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "utility.h"
#include "login.h"
char* ip_search(void) {
	int fd = socket(AF_INET, SOCK_DGRAM, 0);
	if (fd < 0)
		return "";
	struct ifreq request[16];
	struct ifconf ifconfig;
	ifconfig.ifc_len = sizeof(request);
	ifconfig.ifc_buf = (caddr_t) request;
	if (ioctl(fd, SIOCGIFCONF, (char *) &ifconfig))
		return "";
	int length = ifconfig.ifc_len / sizeof(struct ifreq);
	while (length-- > 0 && ioctl(fd, SIOCGIFADDR, (char *) &request[length]))
		;
	close(fd);
	return inet_ntoa(((struct sockaddr_in*) (&request[length].ifr_addr))-> sin_addr);
}
char* get_remote_ip(int socket_connect) {
	struct sockaddr_in address;
	memset(&address, 0, sizeof(address));
	int length = sizeof(address);
	getpeername(socket_connect, (struct sockaddr *) &address, &length);
	return inet_ntoa(address.sin_addr);
}
void change_ip_address(char* ip) {
	while (*ip++) {
		if (*ip == '.') {
			*ip = ',';
		}
	}
}

void send_cmd(int fd, char* cmd) {
	printf("ftp>%s", cmd);
	send(fd, cmd, strlen(cmd), 0);
}
void recv_cmd(int fd, char* buffer, int len) {
	int length;
	if ((length = recv(fd, buffer, len, 0)) == -1) {
		perror("recv()");
		exit(1);
	}
	buffer[length] = '\0';
}
void recv_result(int fd, char* key, char* result) {
	char buffer[1024] = { '\0' };
	int length;
	while ((length = recv(fd, buffer, 1024, 0)) != -1) {
		buffer[length] = '\0';
		strcat(result, buffer);
		if (contains(buffer, key)) {
			break;
		}
	}
}

int create_socket() {
	int fd;
	int flag = 1, len = sizeof(int);
	if ((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket()");
		exit(1);
	}
	int timeout = 3;
	setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, (char *) &timeout, sizeof(int));
	setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &timeout, sizeof(int));

	if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &flag, len) == -1) {
		perror("setsockopt");
		exit(1);
	}
	printf("--------------create socket %i \n", fd);
	return fd;
}

void create_remote_address(int port, char* ip, struct sockaddr_in* result) {
	struct sockaddr_in address = *result;
	bzero(&address, sizeof(address));
	address.sin_family = AF_INET;
	address.sin_port = htons(port);
	struct hostent *host;
	if ((host = gethostbyname(ip)) == NULL) {
		perror("gethostbyname()");
		exit(1);
	}
	address.sin_addr = *((struct in_addr*) host->h_addr_list[0]);
	*result = address;
}

int create_connect(char* ip, int port) {
	char message[256] = { '\0' };
	int fd = create_socket();
	struct sockaddr_in address;
	create_remote_address(port, ip, &address);
	sprintf(message, "----------- create address %s:%i \n", ip, port);
	set_commond_info(message);
	if (connect(fd, (struct sockaddr *) &address, sizeof(struct sockaddr)) == -1) {
		perror("connect()");
		exit(1);
	}
	sprintf(message, "connect to %s:%i\n", ip, port);
	set_commond_info(message);
	return fd;
}

void create_local_address(int port, struct sockaddr_in * result) {
	struct sockaddr_in address_server = *result;
	bzero(&address_server, sizeof(address_server));
	address_server.sin_family = AF_INET;
	address_server.sin_port = htons(port);
	address_server.sin_addr.s_addr = htonl(INADDR_ANY);
	*result = address_server;
}

int open_bind(int port) {
	char message[256] = { '\0' };
	struct sockaddr_in address_server;
	create_local_address(port, &address_server);
	int fd_socket = create_socket();
	sprintf(message, "------------bind socket %i address %p %i \n", fd_socket, address_server.sin_addr.s_addr, port);
	set_commond_info(message);
	unsigned int value = 0x1;
	setsockopt(fd_socket, SOL_SOCKET, SO_REUSEADDR, (void *) &value, sizeof(value));
	if (bind(fd_socket, (struct sockaddr *) &address_server, sizeof(struct sockaddr)) == -1) {
		perror("Bind error.");
		exit(1);
	}
	sprintf(message, "------------listen socket %i address %p %i \n", fd_socket, address_server.sin_addr.s_addr, port);
	set_commond_info(message);
	if (listen(fd_socket, 2) == -1) {
		perror("listen() error\n");
		exit(1);
	}
	return fd_socket;
}

int get_pasv_port(char* str) {
	int part1 = 0;
	int part2 = 0;
	char* pointer = strtok(str, ",");
	while (pointer != NULL) {
		part1 = part2;
		part2 = atoi(pointer);
		pointer = strtok(NULL, ",");
	}
	return part1 * 256 + part2;
}

void create_port_comment(char* port_cmd) {
	port_plus();
	int part1 = 0;
	while (get_port() > (part1 * 256)) {
		part1++;
	}
	part1--;
	int padding = get_port() - (part1 * 256);
	unsigned char local_ip[20];
	strcpy(local_ip, ip_search());
	change_ip_address(local_ip);
	sprintf(port_cmd, "PORT %s,%i,%i\r\n", local_ip, part1, padding);
}

void ltrim(char string[]) {
	char* pos = string;
	while (*pos == ' ' || *pos == '\t') {
		*pos++;
	}
	strcpy(string, pos);
}

void rtrim(char string[]) {
	int pos = strlen(string) - 1;
	while ((string[pos] == ' ' || string[pos] == '\t') && pos >= 0) {
		pos--;
	};
	string[pos + 1] = '\0';
}

void trim(char *string) {
	ltrim(string);
	rtrim(string);
}

char* substr(char* const str, int const position, int const length) {
	char result[100] = { '\0' };
	int end_position = position + length;
	int i, j;
	for (i = position, j = 0; i <= end_position; i++, j++) {
		result[j] = str[i];
	}
	result[length] = '\0';
	return result;
}

void substring(char str[], char start[100], char end[100], char* result) {
	char *pfirst = strstr(str, start);
	char *psecond = strstr(pfirst + 1, end);
	int first = pfirst - str + 1;
	int j;
	for (j = 0; first < psecond - str; first++, j++) {
		result[j] = str[first];
	}
	result[j] = '\0';
}

int file_put_contents(char* path, char* string) {
	FILE* fd;
	if ((fd = fopen(path, "wb")) == NULL) {
		printf("Error!\n");
		return -1;
	}
	fseek(fd, 0, SEEK_SET);
	fputs(string, fd);
	fclose(fd);
	return 0;
}

int contains(char* string, char* substring) {
	char* part = strtok(string, " \r\n\t");
	while (part != NULL) {
		if (!strcmp(substring, part)) {
			return 1;
		}
		part = strtok(NULL, " \r\n\t");
	}
	return 0;
}

